package com.shadowlight.hero_story.cmdHandler;

import com.shadowlight.hero_story.msg.GameMsgProtocol;
import com.shadowlight.hero_story.rank.RankItem;
import com.shadowlight.hero_story.rank.RankService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;


/**
 * @Description 获取排名
 * @Author cz
 * @Date 2022/3/22
 */
public class GetRankCmdHandler implements ICmdHandler<GameMsgProtocol.GetRankCmd> {

    @Override
    public void handle(ChannelHandlerContext channelHandlerContext, GameMsgProtocol.GetRankCmd msg) {
        Integer currentUserId = (Integer) channelHandlerContext.channel().attr(AttributeKey.valueOf("userId")).get();
        if (currentUserId == null) {
            return;
        }

        RankService.getInstance().getRankItemsFromRedis(rankItems -> {
            GameMsgProtocol.GetRankResult.Builder rankResultBuilder = GameMsgProtocol.GetRankResult.newBuilder();
            for (RankItem item : rankItems) {
                GameMsgProtocol.GetRankResult.RankItem.Builder rankItemBuilder = GameMsgProtocol.GetRankResult.RankItem.newBuilder();
                rankItemBuilder.setRankId(item.getRankId());
                rankItemBuilder.setUserId(item.getUserId());
                rankItemBuilder.setUserName(item.getUserName());
                rankItemBuilder.setHeroAvatar(item.getHeroAvatar());
                rankItemBuilder.setWin(item.getWin());
                rankResultBuilder.addRankItem(rankItemBuilder.build());
            }

            channelHandlerContext.writeAndFlush(rankResultBuilder.build());
        });


    }
}
